package com.zoke.dappstore.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.arialyy.aria.core.Aria;
import com.google.gson.Gson;
import com.vector.update_app.HttpManager;
import com.vector.update_app.UpdateAppManager;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zoke.dappstore.R;
import com.zoke.dappstore.base.NebActivity;
import com.zoke.dappstore.dialog.UpdateDialog;
import com.zoke.dappstore.fragment.MainF;
import com.zoke.dappstore.fragment.RankF;
import com.zoke.dappstore.model.Version;
import com.zoke.dappstore.tools.TintManager;
import com.zoke.dappstore.tools.Tools;
import com.zoke.dappstore.tools.UpdateService;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.Map;

@ContentView(R.layout.activity_main)
public class MainActivity extends NebActivity {

    private MainF mainF;
    private RankF mineF;

    @ViewInject(R.id.iv_main)
    ImageView iv_main;
    @ViewInject(R.id.iv_mine)
    ImageView iv_mine;
    @ViewInject(R.id.tv_main)
    TextView tv_main;
    @ViewInject(R.id.tv_mine)
    TextView tv_mine;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemFragment(R.id.ll_main);
        mTitleBar.setRight(R.drawable.ic_file_download, v -> MainActivity.this.
                startActivity(new Intent(MainActivity.this, DmActivity.class)));
        getVersion();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mainF != null) transaction.hide(mainF);
        if (mineF != null) transaction.hide(mineF);
    }

    @Event({R.id.ll_main, R.id.ll_mine})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_main:
                itemFragment(R.id.ll_main);
                mTitleBar.setTitle(R.string.app_name);
                break;
            case R.id.ll_mine:
                itemFragment(R.id.ll_mine);
                mTitleBar.setTitle("Dapp榜单");
                break;
        }
    }

    private void getVersion() {
        get("getVersion", new String[]{}, Tools.getAddress(), new SmartCallback() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject jo = jsonObject.getJSONObject("result");
                    String res = jo.optString("result");
                    LogUtil.e("result = " + res);
                    if (!TextUtils.isEmpty(res)) {
                        Version version = new Gson().fromJson(res, Version.class);
                        if (version == null) return;
                        int appCode = Tools.getVersionCode(MainActivity.this);
                        LogUtil.e("当前版本号：" + appCode);
                        if (appCode < version.vcode) {
                            //版本升级
                            showUpdateDialog(version);
                        }
                    }


                } catch (Exception e) {
                    LogUtil.e(e.toString());
                }
            }

            @Override
            public void onError(String error) {

            }
        });
    }

    private void showUpdateDialog(final Version version) {
        final UpdateDialog updateDialog = new UpdateDialog(this);
        updateDialog.setClickListener(new UpdateDialog.ButtonClickListener() {
            @Override
            public void onSureClick() {
                AndPermission.with(MainActivity.this)
                        .runtime()
                        .permission(Permission.Group.STORAGE)
                        .onGranted(permissions -> {
                            // Storage permission are allowed.
                            updateDialog.disDialog();
                            Intent intent = new Intent(MainActivity.this, UpdateService.class);
                            intent.putExtra("apkUrl", version.url);
                            startService(intent);
                        })
                        .onDenied(permissions -> {
                            // Storage permission are not allowed.
                        })
                        .start();
            }

            @Override
            public void onCancelClick() {

            }
        });
        updateDialog.showDialog();
        updateDialog.showDesc(version.desc, "新版本", "取消");
    }

    public class UpdateAppHttpUtil implements HttpManager {

        @Override
        public void asyncGet(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack) {
            RequestParams xParams = new RequestParams(url);
            for (String key : params.keySet()) {
                xParams.addQueryStringParameter(key, params.get(key));
            }
            x.http().get(xParams, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    callBack.onResponse(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    callBack.onError(ex.toString());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }

        @Override
        public void asyncPost(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack) {
            RequestParams xParams = new RequestParams(url);
            for (String key : params.keySet()) {
                xParams.addBodyParameter(key, params.get(key));
            }
            x.http().post(xParams, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    callBack.onResponse(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    callBack.onError(ex.toString());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }

        @Override
        public void download(@NonNull String url, @NonNull String path, @NonNull String fileName, @NonNull FileCallback callback) {
            RequestParams xParams = new RequestParams(url);
            xParams.setSaveFilePath(path);
            x.http().post(xParams, new org.xutils.common.Callback.ProgressCallback<File>() {
                @Override
                public void onSuccess(File result) {
                    callback.onResponse(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    callback.onError(ex.toString());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {
                    callback.onBefore();
                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    callback.onProgress(current, total);
                }
            });
        }
    }


    public void itemFragment(int id) {
        //重置选项+隐藏所有Fragment
        item(id);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragments(transaction);
        switch (id) {
            case R.id.ll_main:
                if (mainF == null) {
                    mainF = new MainF();
                    transaction.add(R.id.container, mainF);
                } else {
                    transaction.show(mainF);
                }
                break;
            case R.id.ll_mine:
                if (mineF == null) {
                    mineF = new RankF();
                    transaction.add(R.id.container, mineF);
                } else {
                    transaction.show(mineF);
                }
                break;
        }
        transaction.commit();
    }


    private void item(int id) {
        TintManager.setTint(iv_main, getResources().getColor(id == R.id.ll_main ? R.color.baseColor : R.color.text_hint));
        TintManager.setTint(iv_mine, getResources().getColor(id == R.id.ll_mine ? R.color.baseColor : R.color.text_hint));
        tv_main.setSelected(id == R.id.ll_main);
        tv_mine.setSelected(id == R.id.ll_mine);
    }


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        initBar(R.id.status, false);
    }


}
